package com.app.action.concurrent;

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;

public class CyclicBarrierAction {
    private static final int N = 10;

    public static void main(String[] args) {

        CyclicBarrier barrier = new CyclicBarrier(N, new Runnable() {
            @Override
            public void run() {
                System.out.println("---all threads have reached barrier state");
            }
        });
        for (int i = 0; i < N; i++) {
            new Thread(new WorkRunnable(barrier)).start();
        }

    }
}

class WorkRunnable implements Runnable {
    private CyclicBarrier barrier;

    public WorkRunnable(CyclicBarrier barrier) {
        this.barrier = barrier;
    }

    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName() + " start runnning!!");
        try {
            Thread.sleep((long) ((Math.random() * 30 * 1000)));
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        try {
            System.out.println(Thread.currentThread().getName() + " step into barrier state !!");
            barrier.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (BrokenBarrierException e) {
            e.printStackTrace();
        }
        System.out.println(Thread.currentThread().getName() + " continue to run!!");

    }
}
